package com.infitecs.eyas.security;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.infitecs.eyas.common.ajax.DataTablesPage;
import com.infitecs.eyas.common.ajax.DataTablesResponse;
import com.infitecs.eyas.develop.model.PermissionTreeNode;
import com.infitecs.eyas.develop.service.PermissionService;
import com.infitecs.eyas.security.model.Role;
import com.infitecs.eyas.security.model.User;
import com.infitecs.eyas.security.service.RoleService;
import com.infitecs.eyas.security.service.UserService;
import com.infitecs.krill.ajax.response.AjaxResponse;
import com.infitecs.krill.constant.Constant;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("/security/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    @RequestMapping(method = RequestMethod.GET)
    @RequiresPermissions("security:user:open")
    public String user(Model model, HttpServletRequest request) throws JsonProcessingException {
        List<Role> roleList = roleService.getRoleList();
        model.addAttribute("roleList", roleList);
        List<PermissionTreeNode> permissionTreeNodes = permissionService.getPermissionTree();
        model.addAttribute("tree", new ObjectMapper().writeValueAsString(permissionTreeNodes));
        return "security/user";
    }

    @RequestMapping("/getUserListPage")
    @ResponseBody
    @RequiresPermissions("security:user:open")
    public DataTablesResponse getUserListPage(User user, DataTablesPage page) {
        return new DataTablesResponse(page, userService.getUserListPage(page,user));
    }

    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("security:user:open")
    public AjaxResponse addUser(@RequestBody @Valid User user, BindingResult result, HttpSession session) {
        if (result.hasErrors()) {
            return new AjaxResponse(result);
        }
        return AjaxResponse.getInstanceByResult(userService.addUser(user), session);
    }

    @RequestMapping(value = "/{userId}", method = RequestMethod.GET)
    @ResponseBody
    @RequiresPermissions("security:user:open")
    public AjaxResponse getUser(@PathVariable String userId) throws JsonProcessingException {
        AjaxResponse ajaxResponse = new AjaxResponse();
        User user = userService.getUser(userId);
        ajaxResponse.addAttribute("user", user);
        ajaxResponse.addAttribute("roleList", userService.getRolesByUsername(user.getUsername()));
        return ajaxResponse;
    }

    @RequestMapping(method = RequestMethod.PUT)
    @ResponseBody
    @RequiresPermissions("security:user:open")
    public AjaxResponse updateUser(@RequestBody @Valid User user, BindingResult result, HttpSession session) {
        if (result.hasErrors()) {
            return new AjaxResponse(result);
        }
        int affectedLineNum = userService.updateUser(user);
        return AjaxResponse.getInstanceByResult(affectedLineNum == Constant.AFFECTED_LINE_1, session);
    }

    @RequestMapping(value = "/{userId}", method = RequestMethod.DELETE)
    @ResponseBody
    @RequiresPermissions("security:user:open")
    public AjaxResponse deleteUser(@PathVariable String userId, HttpSession session) {
        return AjaxResponse.getInstanceByResult(userService.deleteUser(userId), session);
    }

    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResponse updatePassword(String oldPassword, String newPassword, HttpSession session) {
        String loginName = SecurityUtils.getSubject().getPrincipal().toString();
        int affectedLineNum = userService.updatePassword(loginName, oldPassword, newPassword);
        return AjaxResponse.getInstanceByResult(affectedLineNum == Constant.AFFECTED_LINE_1, session);
    }
}
